<?php 


/**
 * Class MongoLConnection
 * @author hwz
 */
class MongoLConnection {


    /**
     * 连接实例
     *
     * @var array
     */
    private static $instances;

    /**
     * MongoClient
     *
     * @var MongoClient
     */
    private $connection;

    /**
     * 数据库
     *
     * @var MongoDB
     */
    public $database;

    public function __construct($config,$name='default') {
        $this->connection = new MongoClient($this->_dns($config));
        if (isset($config['dbname'])) {
            $this->setDB($config['dbname']);
        }
        self::$instances[$name] = $this;
    }

    /**
     * 生成数据库连接字符串
     *
     * @return string
     * @author hwz
     **/
    private function _dns($config) {
        if (!isset($config['host'])) {
            $config['host'] = MongoClient::DEFAULT_HOST;
        }
        if (!isset($config['port'])) {
            $config['port'] = MongoClient::DEFAULT_PORT;
        }

        return "mongodb://{$config['host']}:{$config['port']}";
    }

    /**
     * 获得一个连接
     *
     * @param string $name 连接别名
     * @return MongoLConnection
     * @author hwz
     **/
    public static function get($name='default') {
        if (isset(self::$instances[$name])) {
            return self::$instances[$name];
        }
        return new MongoLConnection(array());
    }

    /**
     * 设置一个数据库
     *
     * @param string $dbname
     * @return MongoDB
     * @author hwz
     **/
    public function setDB($dbname) {
        return $this->database = $this->connection->selectDb($dbname);
    }

    /**
     * 将本类不存在的方法代理到MongoClient实例中
     *
     * @param string $method
     * @param mixed $parameters
     * @return mixed
     * @author hwz
     **/
    public function __call($method,$parameters) {
        return call_user_func_array(array( $this->connection,$method ),$parameters);
    }

    /**
     * 设置模型文件路径，使模型文件可以自动加载 
     *
     * @param string $path 
     * @return void
     * @author hwz
     **/
    public function setModelPath($path) {
        $this->modelPath = $path;
        spl_autoload_register(array($this,'includeModel'));
    }

    /**
     * 加载文件
     *
     * @param string $name 文件全路径
     * @return void
     * @author hwz
     **/
    public function includeModel($name) {
        $model =  $this->modelPath . $name . '.php';
        if (file_exists($model)) {
            require_once($model);
        }
    }
}


//end of file
